<template>
  <view class="min-h-screen bg-gray-50 pb-[240rpx]">
    <!-- 自定义状态栏 -->
    <view class="bg-orange-500 h-[88rpx]"></view>
    
    <!-- 自定义导航栏 -->
    <view class="bg-orange-500 px-[32rpx] py-[24rpx]">
      <text class="text-[36rpx] font-bold text-white">购物车</text>
    </view>

    <!-- 空购物车状态 -->
    <view v-if="cartItems.length === 0" class="flex flex-col items-center justify-center h-screen">
      <image 
        :src="defaultProductImage" 
        class="w-[200rpx] h-[200rpx] opacity-50 mb-[32rpx]"
        mode="aspectFit"
      />
      <text class="text-[32rpx] text-gray-500 mb-[48rpx]">购物车空空的~</text>
      <view 
        class="bg-orange-500 px-[48rpx] py-[24rpx] rounded-[8rpx]"
        @tap="goToHome"
      >
        <text class="text-[32rpx] font-medium text-white">去逛逛</text>
      </view>
    </view>

    <!-- 购物车商品列表 -->
    <view v-else class="px-[32rpx] py-[32rpx]">
      <!-- 全选操作 -->
      <view class="flex items-center justify-between mb-[20rpx]">
        <view class="flex items-center">
          <text class="text-[32rpx] text-gray-600 mr-[32rpx]">共{{ cartItems.length }}件商品</text>
        </view>
        <view class="flex items-center">
          <text 
            class="text-[28rpx] text-red-500 cursor-pointer"
            @tap="clearCart"
          >
            清空购物车
          </text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="space-y-[20rpx]">
        <view 
          v-for="item in cartItems" 
          :key="item.id"
          class="bg-white rounded-[16rpx] p-[24rpx]"
        >
          <view class="flex items-start">
            <!-- 选择框 -->
            <view 
              class="w-[40rpx] h-[40rpx] rounded-[8rpx] border-2 flex items-center justify-center mr-[16rpx] mt-[8rpx]"
              :class="item.selected ? 'border-orange-500 bg-orange-500' : 'border-gray-300 bg-white'"
              @tap="toggleItemSelection(item)"
            >
              <text v-if="item.selected" class="text-[24rpx] text-white">✓</text>
            </view>
            
            <!-- 商品图片 -->
            <image 
              :src="item.image" 
              class="w-[180rpx] h-[180rpx] rounded-[12rpx] object-cover mr-[24rpx]"
              mode="aspectFill"
            />
            
            <!-- 商品信息 -->
            <view class="flex-1">
              <text class="text-[32rpx] font-medium text-gray-800 block mb-[8rpx]">{{ item.name }}</text>
              <text class="text-[36rpx] font-bold text-red-500 block mb-[16rpx]">¥{{ item.price }}</text>
              
              <!-- 数量控制和删除 -->
              <view class="flex items-center justify-between">
                <view class="flex items-center">
                  <view 
                    class="w-[60rpx] h-[60rpx] rounded-[8rpx] border border-gray-300 flex items-center justify-center"
                    @tap="decreaseQuantity(item)"
                  >
                    <text class="text-[32rpx] text-gray-600">-</text>
                  </view>
                  <text class="mx-[24rpx] text-[32rpx] font-medium">{{ item.quantity }}</text>
                  <view 
                    class="w-[60rpx] h-[60rpx] rounded-[8rpx] bg-orange-500 flex items-center justify-center"
                    @tap="increaseQuantity(item)"
                  >
                    <text class="text-[32rpx] text-white">+</text>
                  </view>
                </view>
                <text 
                  class="text-[28rpx] text-red-500 cursor-pointer"
                  @tap="removeFromCart(item)"
                >
                  删除
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 推荐商品 -->
      <view v-if="recommendProducts.length > 0" class="mt-[40rpx]">
        <text class="text-[36rpx] font-bold text-gray-800 block mb-[32rpx]">猜你喜欢</text>
        <view class="grid grid-cols-2 gap-[24rpx]">
          <view 
            v-for="product in recommendProducts" 
            :key="product.id"
            class="bg-white rounded-[24rpx] p-[24rpx]"
            @tap="goToProductDetail(product)"
          >
            <image 
              :src="product.image" 
              class="w-full h-[240rpx] object-cover rounded-[16rpx] mb-[16rpx]"
              mode="aspectFill"
            />
            <text class="text-[28rpx] font-medium text-gray-800 block mb-[12rpx]">{{ product.name }}</text>
            <text class="text-[32rpx] font-bold text-red-500">¥{{ product.price }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view 
      v-if="cartItems.length > 0" 
      class="fixed left-0 right-0 bg-white border-t border-gray-200 px-[32rpx] py-[24rpx] z-40"
      style="bottom: 0;"
    >
      <!-- 全选和合计 -->
      <view class="flex items-center justify-between mb-[16rpx]">
        <view class="flex items-center">
          <view 
            class="w-[40rpx] h-[40rpx] rounded-[8rpx] border-2 flex items-center justify-center mr-[16rpx]"
            :class="selectAll ? 'border-orange-500 bg-orange-500' : 'border-gray-300 bg-white'"
            @tap="onSelectAllChange"
          >
            <text v-if="selectAll" class="text-[24rpx] text-white">✓</text>
          </view>
          <text class="text-[28rpx] text-gray-800">全选</text>
        </view>
        <view class="flex items-center">
          <text class="text-[24rpx] text-gray-500 mr-[8rpx]">合计：</text>
          <text class="text-[36rpx] font-bold text-red-500">¥{{ totalPrice.toFixed(2) }}</text>
        </view>
      </view>
      
      <!-- 结算按钮组 -->
      <view class="flex gap-[16rpx]">
        <view 
          class="flex-1 h-[88rpx] bg-white border-2 border-orange-500 rounded-[8rpx] flex items-center justify-center"
          :class="selectedItems.length === 0 ? 'opacity-50' : 'cursor-pointer'"
          @tap="processPayment"
        >
          <text class="text-[32rpx] font-medium text-orange-500">立即支付</text>
        </view>
        <view 
          class="flex-1 h-[88rpx] bg-orange-500 rounded-[8rpx] flex items-center justify-center"
          :class="selectedItems.length === 0 ? 'opacity-50' : 'cursor-pointer'"
          @tap="goToCheckoutPage"
        >
          <text class="text-[32rpx] font-medium text-white">
            {{ selectedItems.length === 0 ? '请选择商品' : `去结算(${selectedItems.length})` }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { useCartStore } from '@/stores/cart'

/**
 * 购物车页面 - 管理选中商品和结算
 * 性能优化：使用计算属性自动更新总价，防抖操作防止频繁点击
 */

interface CartItem {
  id: number
  name: string
  price: number
  image: string
  quantity: number
  selected: boolean
}

interface Product {
  id: number
  name: string
  price: number
  image: string
}

const cartStore = useCartStore()

// 响应式数据
const selectAll = ref(false)
const defaultProductImage = 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'

// 购物车商品列表
const cartItems = ref<CartItem[]>([
  {
    id: 1,
    name: '珍珠奶茶',
    price: 18,
    image: defaultProductImage,
    quantity: 2,
    selected: true
  },
  {
    id: 2,
    name: '芒果布丁奶茶',
    price: 22,
    image: defaultProductImage,
    quantity: 1,
    selected: true
  },
  {
    id: 4,
    name: '抹茶拿铁',
    price: 28,
    image: defaultProductImage,
    quantity: 1,
    selected: false
  }
])

// 推荐商品
const recommendProducts = ref<Product[]>([
  {
    id: 6,
    name: '柠檬蜂蜜茶',
    price: 16,
    image: defaultProductImage
  },
  {
    id: 3,
    name: '草莓奶昔',
    price: 25,
    image: defaultProductImage
  }
])

// 计算属性
const selectedItems = computed(() => 
  cartItems.value.filter(item => item.selected)
)

const totalPrice = computed(() => 
  selectedItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
)

// 方法
const toggleItemSelection = (item: CartItem) => {
  item.selected = !item.selected
  calculateTotal()
}

const onSelectAllChange = () => {
  selectAll.value = !selectAll.value
  cartItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

const calculateTotal = () => {
  const allSelected = cartItems.value.every(item => item.selected)
  selectAll.value = allSelected && cartItems.value.length > 0
}

const increaseQuantity = (item: CartItem) => {
  item.quantity++
  // 同步到store
  cartStore.updateQuantity(item.id, item.quantity)
}

const decreaseQuantity = (item: CartItem) => {
  if (item.quantity > 1) {
    item.quantity--
    // 同步到store
    cartStore.updateQuantity(item.id, item.quantity)
  }
}

const removeFromCart = (item: CartItem) => {
  const index = cartItems.value.findIndex(cartItem => cartItem.id === item.id)
  if (index > -1) {
    cartItems.value.splice(index, 1)
    cartStore.removeFromCart(item.id)
  }
  calculateTotal()
}

const clearCart = () => {
  cartItems.value = []
  cartStore.clearCart()
  selectAll.value = false
}

const goToHome = () => {
  Taro.switchTab({
    url: '/pages/home/index'
  })
}

const goToProductDetail = (product: Product) => {
  Taro.navigateTo({
    url: `/pages/product-detail/index?id=${product.id}`
  })
}

const goToCheckout = () => {
  if (selectedItems.value.length === 0) {
    Taro.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    })
    return
  }
  
  // 显示支付方式选择
  showPaymentOptions()
}

const goToCheckoutPage = () => {
  if (selectedItems.value.length === 0) {
    Taro.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    })
    return
  }
  
  // 跳转到结算页面
  const selectedItemsData = JSON.stringify(selectedItems.value)
  Taro.navigateTo({
    url: `/pages/checkout/index?items=${encodeURIComponent(selectedItemsData)}`
  })
}

const showPaymentOptions = () => {
  Taro.showActionSheet({
    itemList: ['立即支付', '去结算页面'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 立即支付
        processPayment()
      } else if (res.tapIndex === 1) {
        // 跳转到结算页面
        const selectedItemsData = JSON.stringify(selectedItems.value)
        Taro.navigateTo({
          url: `/pages/checkout/index?items=${encodeURIComponent(selectedItemsData)}`
        })
      }
    }
  })
}

const processPayment = () => {
  if (selectedItems.value.length === 0) {
    Taro.showToast({
      title: '请选择要支付的商品',
      icon: 'none'
    })
    return
  }
  
  // 显示支付方式选择
  Taro.showActionSheet({
    itemList: ['微信支付', '支付宝支付', '余额支付'],
    success: (res) => {
      const paymentMethods = ['微信支付', '支付宝支付', '余额支付']
      const selectedMethod = paymentMethods[res.tapIndex]
      
      // 确认支付
      Taro.showModal({
        title: '确认支付',
        content: `使用${selectedMethod}支付 ¥${totalPrice.value.toFixed(2)}？\n\n商品明细：\n${selectedItems.value.map(item => `${item.name} x${item.quantity}`).join('\n')}`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            // 模拟支付过程
            Taro.showLoading({
              title: '支付中...'
            })
            
            setTimeout(() => {
              Taro.hideLoading()
              Taro.showToast({
                title: '支付成功！',
                icon: 'success',
                duration: 2000
              })
              
              // 清空选中的商品
              const remainingItems = cartItems.value.filter(item => !item.selected)
              cartItems.value = remainingItems
              calculateTotal()
              
              // 跳转到订单页面
              setTimeout(() => {
                Taro.switchTab({
                  url: '/pages/order/index'
                })
              }, 2000)
            }, 1500)
          }
        }
      })
    }
  })
}

// 生命周期
onMounted(() => {
  calculateTotal()
  console.log('购物车页面加载完成')
})
</script>

<style lang="scss" scoped>
.space-y-\[20rpx\] > view:not(:first-child) {
  margin-top: 20rpx;
}

.cursor-pointer {
  cursor: pointer;
}

.gap-\[16rpx\] {
  gap: 16rpx;
}

.flex-1 {
  flex: 1;
}
</style> 